import re

from openpyxl import load_workbook

from xlstoxml import write_to_string_file

languages_map = {'ar': 'ar', 'cs': 'cs', 'da': 'da', 'de': 'de', 'el': 'el',
                 'es': 'es', 'fi': 'fi', 'fr': 'fr', 'fr-ca': 'fr-rCA', 'hu': 'hu',
                 'it': 'it', 'he': 'iw', 'ja': 'ja', 'ko': 'ko', 'nl': 'nl',
                 'nb': 'nb', 'pl': 'pl', 'pt': 'pt', 'pt-br': 'pt-rBR', 'ro': 'ro',
                 'ru': 'ru', 'sk': 'sk', 'sv': 'sv', 'th': 'th', 'zh': 'zh',
                 'zh-tw': 'zh-rTW'}
gs_language_dir = 'res/gs_language/'
lan_model_file = 'res/extract_lan_model.xlsx'


def main():
    # 键为语言key，值为gslan 序号
    lan_model_dict = {}
    wb = load_workbook(lan_model_file)
    ws = wb['Sheet1']
    # 遍历所有列获取key和gslan 序号，并装载到lan_model_dict
    for ri, row in enumerate(ws.rows):
        if ri == 0:
            continue
        key = row[0].value
        if key is None or key == '':
            continue
        value = row[1].value
        index = value.find(',')
        value = value[:index]
        lan_model_dict[key] = value

    # 遍历需要gslan中的语言，根据序号提取字符串，并合入目标string文件
    for lan in languages_map.keys():
        gs_language_file = gs_language_dir + lan + '.txt'
        lans_dict = {}
        with open(gs_language_file, encoding='utf-8') as fh:
            content = fh.readlines()
            content = ''.join(content)
            for key in lan_model_dict:
                lan_sn = lan_model_dict[key]
                p = re.compile(r'^' + lan_sn + r',(.*$)', re.M)
                res = p.findall(content)
                if len(res) == 0:
                    continue
                lans_dict[key] = res[0]
        print(lan, lans_dict)
        write_to_string_file('res/origin/values-' + languages_map[lan] + '/strings.xml', lans_dict)


if __name__ == '__main__':
    main()
